package com.kly.cashmall.framework.mvp;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.Nullable;

import com.kly.cashmall.baserx.RxManager;

public abstract class BasePresenter<T extends Viewer> implements Presenter {

    protected T viewer;
    private Handler mPresenterHandler = new Handler(Looper.getMainLooper());

    public RxManager rxManager;

    public BasePresenter(T viewer) {
        setViewer(viewer);
        if (rxManager == null) {
            rxManager = new RxManager();
        }
    }

    public @Nullable
    T getViewer() {
        return viewer;
    }

    public void setViewer(@Nullable T viewer) {
        this.viewer = viewer;
    }

    private Handler getPresenterHandler() {
        if (mPresenterHandler == null) {
            mPresenterHandler = new Handler(Looper.getMainLooper());
        }
        return mPresenterHandler;
    }

    public void postDelay(Runnable runnable, int delay) {
        getPresenterHandler().postDelayed(runnable, delay);
    }

    public void runOnUiThread(Runnable runnable) {
        getPresenterHandler().post(runnable);
    }

    public Activity getActivity() {
        Activity activity = viewer == null ? null : viewer.getActivity();
        if (activity != null && !activity.isFinishing()) {
            return activity;
        }
        return null;
    }

    @Override
    public int priority() {
        return 0;
    }

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {
        if (rxManager != null) {
            rxManager.clear();
        }
        viewer = null;
    }

    @Override
    public void _willDestroy() {
        if (mPresenterHandler != null) {
            mPresenterHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void newIntent(Intent intent) {

    }

    @Override
    public void activityResult(int requestCode, int resultCode, Intent data) {

    }
}